package org.graffitidiary.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.graffitidiary.activity.AutoDrawActivity;
import org.graffitidiary.activity.FileListActivity;
import org.graffitidiary.activity.MainActivity;
import org.graffitidiary.bean.Brush;
import org.graffitidiary.bean.FileInfo;
import org.graffitidiary.bean.PathXY;
import org.graffitidiary.bean.Userinfo;
import org.graffitidiary.manager.Dbs;
import org.graffitidiary.utils.GloableParams;
import org.graffitidiary.utils.MD5;

import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

public class DrawView extends View {
    private static final float TOUCH_TOLERANCE = 4;
    //屏幕宽高
    private int width;
    private int height;
    private Paint paint;
    private Path path;
    //保存之前画的路径
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private List<Brush> brushs = new ArrayList<Brush>();
    private Brush brush;//笔的设置和坐标的集合
    private List<PathXY> list = new ArrayList<PathXY>();
    private PathXY pathXY;//坐标

    private int selectColor = Color.BLACK;//用户选择的颜色

    public DrawView(Context context, AttributeSet set) {
        super(context, set);

        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();//获取屏幕宽
        height = wm.getDefaultDisplay().getHeight();//获取屏幕高

        initCanvas();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 将前面已经画过得显示出来
        canvas.drawBitmap(mBitmap, 0, 0, paint);
        if (path != null) {
            // 实时的显示
            canvas.drawPath(path, paint);
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float currentX = event.getX();
        float currentY = event.getY();
        float X = currentX / width;//计算绘制的坐标占屏幕百分比用于适配其它用户屏幕
        float Y = currentY / height;
        pathXY = new PathXY();
        pathXY.setX(X);
        pathXY.setY(Y);
        list.add(pathXY);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN : {
                path = new Path();
                setPaintStyle(selectColor);
                // 画线函数，移动到点(currentX, currentY)
                touch_start(currentX, currentY);
                System.out.println("Down=X:" + currentX + ",Y:" + currentY );
                break;
            }
            case MotionEvent.ACTION_MOVE : {
                // 画线函数，连线到点(currentX, currentY)
                touch_move(currentX, currentY);
                mCanvas.drawPath(path, paint);
                System.out.println("MOVE=X:" + currentX + ",Y:" + currentY );
                break;
            }
            case MotionEvent.ACTION_UP : {
                System.out.println("UP=X:" + currentX + ",Y:" + currentY );
                brush = new Brush();
                brush.setPathXY(list);
                brush.setColor(selectColor);
                brush.setStrokeWidth(StrokeWidth/width);
                brushs.add(brush);
                list = new ArrayList<PathXY>();
                break;
            }
        }

        // 刷新界面，调用onDraw()
        invalidate();
        // true表明该事件已经处理完毕，不能返回super.onTouchEvent(event)
        return true;
    }


    private float mX, mY;// 临时点坐标
    private void touch_start(float x, float y) {
        path.moveTo(x, y);
        mX = x;
        mY = y;
    }
    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(mY - y);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
    }

    /**
     * 保存文件
     * @param name
     */
    public FileInfo save(String name) {
        if(brushs.size() == 0){
            return null;
        }

        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
        String time=format.format(date);
        String destFileName = time + ".xml";
        //对文件的处理，得到文件路径，创建文件
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GraffitiDiary/data";
        //创建文件夹
        File dir = new File(path);
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        File file = new File(dir, destFileName);
        try {
            if(writeTxtFile(brushs, file)){//将创建的文件的数据获取过来
                FileInfo fileInfo = new FileInfo();
                fileInfo.setFileNick(name);
                fileInfo.setFileName(destFileName);
                fileInfo.setFilePath(file.getPath());
                fileInfo.setFileState(0);
                insertUserInfo(fileInfo);
                return fileInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将文件信息存储到数据库中
     * @param fileInfo
     */
    private void insertUserInfo(FileInfo fileInfo) {
        Dbs.getDb();
        try {
            Dbs.getDb().createTableIfNotExist(FileInfo.class);
            Dbs.getDb().save(fileInfo);
            Dbs.close();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    // 清屏
    public void clear() {
//		// 清除绘制路径
        path = new Path();
        path.reset();
//		// 刷新界面
        invalidate();
        brushs = new ArrayList<Brush>();

        initCanvas();
    }

    /**
     * 将绘制的东西存到xml中
     * @param brushs
     * @param fileName
     * @return
     * @throws Exception
     */
    public static boolean writeTxtFile(List<Brush> brushs,File  fileName)throws Exception{
        String content = "[";
        for (int i = 0; i < brushs.size(); i++) {
            String content2 = "";
            content += "{\"Brush\":{"
                    + "\"StrokeWidth\":" + brushs.get(i).getStrokeWidth() + ","
                    + "\"Color\":" + brushs.get(i).getColor() + ","
                    + "\"PathXY\":[";
            for (int j = 0; j < brushs.get(i).getPathXY().size(); j++) {
                content2 += "{\"X\":" + brushs.get(i).getPathXY().get(j).getX() + ","
                        + "\"Y\":" + brushs.get(i).getPathXY().get(j).getY() + "},";
            }
            content2 = content2.substring(0, content2.length() - 1);
            content += content2;
            content += "]}},";
        }
        content = content.substring(0, content.length() - 1);
        content += "]";
        RandomAccessFile mm=null;
        boolean flag=false;
        FileOutputStream o=null;
        try {
            o = new FileOutputStream(fileName);
            o.write(content.getBytes("GBK"));
            o.close();
            flag=true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(mm!=null){
                mm.close();
            }
        }
        return flag;
    }

    /**
     * 改变画笔颜色
     * @param color
     */
    public void setPaintColor(int color) {
        this.selectColor = color;
    }

    /**
     * 改变画笔粗细
     * @param Size
     */
    public void setPaintStrokeWidth(float Size){
        this.StrokeWidth = Size;
    }

    float StrokeWidth = 5;

    /**
     * 设置画笔的样式
     * @param selectColor
     */
    public void setPaintStyle(int selectColor) {
        // 创建画笔
        paint = new Paint();
        // 画笔颜色
        paint.setColor(selectColor);
        // 画笔粗细
        paint.setStrokeWidth(StrokeWidth);
        // 抗锯齿
        paint.setAntiAlias(true);
        // 描边，不填充
        paint.setStyle(Paint.Style.STROKE);
        // 设置外边缘
        paint.setStrokeJoin(Paint.Join.ROUND);
        // 形状
        paint.setStrokeCap(Paint.Cap.ROUND);
    }

    private void initCanvas() {
        setPaintStyle(Color.BLACK);
        paint = new Paint(Paint.DITHER_FLAG);
        //保存之前画的数据
        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mBitmap.eraseColor(Color.argb(0, 0, 0, 0));
        mCanvas = new Canvas(mBitmap);  //所有mCanvas画的东西都被保存在了mBitmap中
        mCanvas.drawColor(Color.TRANSPARENT);
    }
}
